package com.example.zhaoping.component;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.zhaoping.entity.Enterprise;
import com.example.zhaoping.entity.Message;
import com.example.zhaoping.entity.User;
import com.example.zhaoping.serviceImpl.EnterpriseServiceImpl;
import com.example.zhaoping.serviceImpl.MessageServiceImpl;
import com.example.zhaoping.serviceImpl.UserServiceImpl;
import com.example.zhaoping.util.TokenException;
import com.example.zhaoping.util.TokenUtil;

import org.checkerframework.checker.units.qual.A;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/chatserver/{user}/{userid}/{token}")
@Component
public class WebSocketServer {
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext context){
        applicationContext = context;
    }

    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private EnterpriseServiceImpl enterpriseService;
    @Autowired
    private TokenUtil tokenUtil = new TokenUtil();

    private static MessageServiceImpl messageService;
    @Autowired
    public void setMessageServiceImpl (MessageServiceImpl messageService){
        WebSocketServer.messageService = messageService;
    }


    //当前在线连接数
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session, @PathParam("user") String user,@PathParam("userid") String userid,@PathParam("token") String token){
        System.out.println(user);
        System.out.println(userid);
        System.out.println(token);
//        if(!tokenUtil.checkSign(token)){
//            throw new TokenException(401,"未登录,请求前往登录!");
//        }
        String sessionKey = user+"_"+userid;
//        if(user=="user"){
//            User user1 = userService.selectByUserId(Integer.parseInt(userid));
//            sessionKey = user.toString();
//        }else if(user == "enterprise"){
//            Enterprise enterprise = enterpriseService.selectById(Integer.parseInt(userid));
//            sessionKey = enterprise.toString();
//        }
        sessionMap.put(sessionKey,session);
        log.info("有新用户加入连接，{},当前连接数：{}",sessionKey,sessionMap.size());
//        JSONObject result = new JSONObject();
//        JSONArray array = new JSONArray();
//        result.set("user",array);
//        for (Object key: sessionMap.keySet()) {
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.set("username",key);
//        }
//        sendAllMessage(JSONUtil.toJsonStr(result));
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("user") String user,@PathParam("userid") String userid,@PathParam("token") String token) {
        String sessionKey = user+"_"+userid;
        sessionMap.remove(sessionKey);
        log.info("有一连接关闭，移除{}的用户session, 当前在线人数为：{}", sessionKey, sessionMap.size());
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("user") String user,@PathParam("userid") String userid,@PathParam("token") String token) {
        //判断用户是否登录
        System.out.println(token);
//        if(!tokenUtil.checkSign(token)){
//            throw new TokenException(401,"未登录,请求前往登录!");
//        }

        JSONObject obj = JSONUtil.parseObj(message);
        String to = obj.getObj("to").toString();
        String table = JSONUtil.parseObj(to).getStr("table");
        String id = JSONUtil.parseObj(to).getStr("id");
        String sessionKey = table+"_"+id;
        String content = obj.getObj("content").toString();

        //保存聊天记录
        Message message1 = new Message();
        message1.setFromId(Integer.parseInt(userid));
        message1.setFromType(user);
        message1.setToType(table);
        message1.setToId(Integer.parseInt(id));
        message1.setCreateTime(new Date());
        message1.setContent(content);
        //设置为未读
        message1.setReaded(0);
        System.out.println(message1);
        WebSocketServer.messageService.insterMessage(message1);

        //发送消息
        Session toSession = sessionMap.get(sessionKey); // 根据 to用户名来获取 session，再通过session发送消息文本
        if (toSession != null) {
            // 服务器端 再把消息组装一下，组装后的消息包含发送人和发送的文本内容
//            Date date = new Date();
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.set("from", sessionKey);  // from 是 zhang
//            jsonObject.set("time",date.toString());
//            jsonObject.set("content", text);  // text 同上面的text
            this.sendMessage(message, toSession);
            log.info("发送给用户[{}]，消息：{}", sessionKey, message);
        } else {
            log.info("发送失败，未找到用户[{}]的session", sessionKey);
        }
    }

    @OnError
    public void onError(Session session,Throwable error){
        log.error("发送错误");
        error.printStackTrace();
    }
    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message,Session toSession) {
        try{
            log.info("服务端给客户端【{}】发送消息{}",toSession.getId(),message);
            toSession.getBasicRemote().sendText(message);
        }catch (Exception e){
            log.error("服务端发送消息给客户端失败!",e);
        }
    }

    //向所有求职者发送消息
    private void sendAllMessage(String message) {
        try{
            for(Session session : sessionMap.values()){
                log.info("服务端给客户端【{}】发送消息{}",session.getId(),message);
            }
        }catch (Exception e){
            log.error("服务端发送消息给客户端失败！",e);
        }
    }

}
